#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
//server

void Usage()
{
    std::cout << "Usage:./udp_server ip port" << std::endl;
}
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage();
        return 1;
    }
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
        std::cout << "socket error" << std::endl;
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    //inet_aton(argv[1],&add.sin_addr);

    if(bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)) != 0)
    {
        std::cout << "bind error" << std::endl;
        return 1;
    }    
    
    while(true)
    {
        char buffer[1024] = {0};
        struct sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        int rn = recvfrom(sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&client_addr,&len);
        std::cout << "收到了多少字节:" << rn << std::endl;
        std::cout << buffer << std::endl;
        std::string ret = "echo" + std::string(buffer);
        int wn = sendto(sockfd,ret.c_str(),ret.size(),0,(struct sockaddr*)&client_addr,sizeof(client_addr));
        std::cout << "发送了多少字节:" << wn << std::endl;    
        sleep(1);     
    }

    return 0;
}